/*
 * 智能门锁模块
 {
    "method":"set"
    "unlock"：“ON”
 }
 {
    "method":"set"
    "open_time"：5000
 }
 *
*/

#include "Arduino.h"  
#include <string.h>  
#include <OneButton.h>       
#include <WiFi.h>
#include <sddc.h>
#include <cJSON.h>
#include <Wire.h>
#include <SDDC_SDK_lib.h>

#define SDDC_CFG_PORT             680U             // SDDC 协议使用的端口号
#define PIN_INPUT                 0                // 选择 IO0 进行控制
#define ESP_TASK_STACK_SIZE       4096
#define ESP_TASK_PRIO             25

static const char* ssid     = "EOS-Tenda";         // WiFi 名
static const char* password = "1234567890";        // WiFi 密码
static const int sign_pin = 12;                    // 锁的状态信号引脚
static const int unlock_pin = 14;                  // 锁的控制引脚
static double opentime = 5000;
static QueueHandle_t lock_mqueue_handle;

OneButton button(PIN_INPUT, true);

static void dev_report_state(char * name)
{
    cJSON * root = cJSON_CreateObject();
    cJSON * array = cJSON_CreateArray();
    cJSON_AddItemToArray(array, cJSON_CreateString(name));
    cJSON_AddItemToObject(root, "obj", array);
    object_report(root);
}

static void lock_task(void *arg)
{
    char *value;

    while (1) {
        if (xQueueReceive(lock_mqueue_handle, (void*)&value, portMAX_DELAY) == SDDC_TRUE) {
            digitalWrite(unlock_pin, HIGH);
            delay(opentime);
            digitalWrite(unlock_pin, LOW);
        }
    }

    vTaskDelete(NULL);
}

/*
 * 锁状态监控函数
 */
static void monitor_task(void *arg)
{
    int newval = 0;
    int oldval = 0;

    // 监控锁开启和关闭状态
    while(1)
    {
        newval = digitalRead(sign_pin);
      
        if(newval != oldval)
        {
            dev_report_state("unlock");
        } 
        oldval = newval;
        delay(100);
    }
}

sddc_bool_t unlock_get(char *objvalue, int value_len)
{
    if(digitalRead(sign_pin))
    {
        strncpy(objvalue, "ON", value_len);
    }else
    {
        strncpy(objvalue, "OFF", value_len);
    }
    
    return SDDC_TRUE;
}

sddc_bool_t opening_time_get(char *objvalue, int value_len)
{
    sprintf(objvalue, "%lf", opentime);
    return SDDC_TRUE;
}

sddc_bool_t unlock_set(const char* value)
{
    if (strcmp(value, "ON") == 0) {
        if(xQueueSend(lock_mqueue_handle, &value, 0) != pdTRUE) {
            return SDDC_FALSE;
        }
    }
    return SDDC_TRUE;
}

sddc_bool_t opening_time_set(const uint64_t value)
{
    // 设置开锁时长
    opentime = value;
    return SDDC_TRUE;
}

/* 
 *  数字量设备对象函数与处理方法注册
 */
NUM_DEV_REGINFO num_dev[] = {
        {"opening_time",opening_time_set},
};

/*
 *  显示设备对象函数与处理方法注册
 */
DIS_DEV_REGINFO dis_dev[] = {
};

/*
 * IO设备对象设置函数与处理方法注册
 */
IO_DEV_REGINFO io_dev[] = {
        {"unlock",unlock_set},
};

/*
 *  系统对象状态获取注册
 */
DEV_STATE_GET  dev_state_get_reg[] = {
        {"unlock",   DEV_IO_TYPE,  unlock_get},
        {"opening_time", DEV_NUM_TYPE, opening_time_get},
};

/*
 *  当前设备的信息定义
 */
DEV_INFO    dev_info = {
            .name     = "智能电磁锁",
            .type     = "device.lock",
            .excl     = SDDC_FALSE,
            .desc     = "ESP-32S + ly03",
            .model    = "IDLOCK01B",
            .vendor   = "inspiration-desktop",
};

/*
 *   系统注册对象汇聚
 */
SDDC_CONFIG_INFO sys_cfg = {
        .token             = "1234567890",            // 设备密码
        .devinfo           = &dev_info,               
        .io_dev_reg        = io_dev,
        .io_dev_reg_num    = ARRAY_SIZE(io_dev),
        .num_dev_reg       = num_dev,
        .num_dev_reg_num   = ARRAY_SIZE(num_dev),
        .state_get_reg     = dev_state_get_reg,
        .state_get_reg_num = ARRAY_SIZE(dev_state_get_reg),
        .dis_dev_reg       = dis_dev,
        .dis_dev_num       = ARRAY_SIZE(dis_dev),
};

/*
 * IO0 按键检测任务
 */
static void esp_io0_key_task()
{
    WiFi.disconnect();
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("WIFI Wait for Smartconfig");
      
        // 设置为Station模式
        WiFi.mode(WIFI_STA);
      
        // 开始智能配网
        WiFi.beginSmartConfig();
        while (1)
        {
            delay(500);
            // 检查智能配网
            if (WiFi.smartConfigDone())
            {
            // 设置自动连接
            WiFi.setAutoConnect(true);  
            break;
            }
        }
    }
}
/*
 * 循环扫描按键
 */
static void esp_tick_task(void *arg)
{
    void *sddc = arg;
    (void)sddc;
    while(1)
    {
      button.tick();
      delay(100);
    }
}

/*
 * 初始化传感器模块
 */
void sensor_init()
{
    pinMode(sign_pin, INPUT);
    pinMode(sign_pin, INPUT_PULLUP);
    pinMode(unlock_pin, OUTPUT);
}

void setup() {
    byte mac[6];
    Serial.begin(115200);
    Serial.setDebugOutput(true);
    Serial.println();

    // 初始化控制模块
    sensor_init();

    // 清除一下按键状态机的状态
    button.reset();
  
    // 创建按键扫描线程，长按 IO0 按键，松开后ESP32 将会进入 SmartConfig 模式
    sddc_printf("长按按键进入 Smartconfig...\n");
    button.attachLongPressStop(esp_io0_key_task);
    
    xTaskCreate(esp_tick_task, "button_tick", ESP_TASK_STACK_SIZE, NULL, ESP_TASK_PRIO, NULL);
    xTaskCreate(monitor_task, "monitor_task", ESP_TASK_STACK_SIZE, NULL, ESP_TASK_PRIO, NULL);
    
    lock_mqueue_handle = xQueueCreate(4, sizeof(char*));
    xTaskCreate(lock_task, "lock_task", ESP_TASK_STACK_SIZE, NULL, ESP_TASK_PRIO, NULL);
    
    // 启动 WiFi 并且连接网络
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) 
    {
        delay(500);
        Serial.print(".");
    }
  
    // 获取并打印 IP 地址
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.print("'ip :");
    Serial.print(WiFi.localIP());
    Serial.println("' to connect");

    // sddc协议初始化
    sddc_lib_main(&sys_cfg);

    // 获取并打印网卡 mac 地址
    WiFi.macAddress(mac);
    sddc_printf("MAC addr: %02x:%02x:%02x:%02x:%02x:%02x\n",
              mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
    // 使用网卡 mac 地址设置设备唯一标识 UID
    sddc_set_uid(G_sddc, mac);
}

void loop() {
    // 运行 SDDC 协议循环
    while (1) 
    {
        sddc_printf("SDDC running...\n");
        sddc_run(G_sddc);
        sddc_printf("SDDC quit!\n");
    }

    // 销毁 SDDC 协议
    sddc_destroy(G_sddc);
}
